/*
 *
 * Saturn Framework Co.Limt
 * Copyright (c) 2012-2019 tanks, Inc. All rights reserved.
 */
 
package com.saturn.config.server.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saturn.config.server.base.R;
import com.saturn.config.server.base.dto.JsonResult;
import com.saturn.config.server.base.entity.AppConfig;
import com.saturn.config.server.base.entity.AppInfo;
import com.saturn.config.server.base.entity.AppVersion;
import com.saturn.config.server.service.AppConfigService;
import com.saturn.config.server.service.AppInfoService;
import com.saturn.config.server.service.AppVersionService;
import com.saturn.config.server.util.YamlPropUtil;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * <dl>
 *    <dt><b>Title:</b></dt>
 *    <dd>
 *    	none
 *    </dd>
 *    <dt><b>Description:</b></dt>
 *    <dd>
 *    	<p>配置历史版本
 *    </dd>
 *
 * @author tanks
 * @date 2019-07-08 14:50:16
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/appversion")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AppVersionController {

	private final AppInfoService appInfoService;
	private final AppConfigService appConfigService;
	private final AppVersionService appVersionService;
	

	/**
	 * 分页查询
	 * 
	 * @param page       分页对象
	 * @param appVersion 配置历史版本
	 * @return
	 */
	@RequestMapping(value = "/page", produces = "application/json")
	public @ResponseBody IPage<?> getAppInfoPage(HttpServletRequest request, Page page, AppInfo appInfo) {
		Map<String, Object> params = WebUtils.getParametersStartingWith(request, StringUtils.EMPTY);
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		if (StringUtils.isNotBlank(start)) {
			page.setCurrent(Long.parseLong(start) / 50 + 1);
		} else {
			page.setCurrent(1l);
		}
		if (StringUtils.isNotBlank(limit)) {
			page.setSize(Long.parseLong(limit));
		} else {
			page.setSize(20l);
		}
		List<String> keys = new ArrayList<String>();
		for (String key : params.keySet()) {
			String value = (String) params.get(key);
			if (StringUtils.isBlank(value)) {
				keys.add(key);
			}
		}
		for (String key : keys) {
			params.remove(key);
		}
		return appVersionService.queryPage(page, params);
	}

	/**
	 * 批量项目配置
	 * @return
	 * @throws BusinessException
	 */
	@RequestMapping(value = "/deleteAppVersion",method = RequestMethod.POST,produces="application/json")
	public @ResponseBody JsonResult deleteAppVersion(@RequestParam("ids") String[] ids) {
		JsonResult response = new JsonResult();
		if( ids==null || ids.length==0 ){
			response.setSuccess(Boolean.FALSE.booleanValue());
			response.setRespMsg("删除失败！");
		}
		try{
			int size = this.appVersionService.deleteAppVersion(ids);
			if( size>0 ){
				response.setSuccess(Boolean.TRUE.booleanValue());
				response.setRespMsg("删除成功,总共" + size + "个版本！");
			}else{
				response.setSuccess(Boolean.FALSE.booleanValue());
				response.setRespMsg("删除失败！");
			}
		}catch(Exception ex){
			log.error("失败",ex);
			response.setSuccess(Boolean.FALSE.booleanValue());
			response.setRespMsg("删除失败");
		}
		return response;
	}

	/** 
	 * 导出应用配置项
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws BusinessException
	 */
	@RequestMapping(value = "exportApplications")
	public void exportApplications(HttpServletRequest request,HttpServletResponse response,String ids,String type) throws IOException {
		if( StringUtils.isBlank(ids) ) return;
		response.setContentType("application/octet-stream");
		// 设置导出Excel的名称
		response.setHeader("Content-disposition", "attachment;filename=" + new String(("yml".equals(type) ? "config.yml":"config.properties").getBytes("GB2312"), "ISO_8859_1"));
		// 刷新缓冲
		response.flushBuffer();
		String[] versionIds = ids.split(",");
		for(String id:versionIds) {
			AppVersion appVersion = this.appVersionService.getById(id);
			if( appVersion==null ) continue;
			AppInfo appInfo = this.appInfoService.getById(appVersion.getAppId());
			QueryWrapper queryWrapper = Wrappers.query();
			queryWrapper.in("app_id", appVersion.getAppId());
			queryWrapper.eq("version", appVersion.getVersion());
			queryWrapper.orderByDesc("app_id","config_key");
			List<AppConfig> list = appConfigService.list(queryWrapper);
			if( list!=null && list.size()>0 ) {
				if( "yml".equals(type) ) {
					Properties props = new Properties();
					for(AppConfig appConfig:list) {
						props.put(appConfig.getConfigKey(), appConfig.getConfigValue());
					}
					String text = YamlPropUtil.properties2Yaml(props);
					response.getOutputStream().write(text.getBytes());
				}else {
					String line = "\r\n";
					byte[] eqs = "=".getBytes();
					byte[] lineByte = line.getBytes();
					response.getOutputStream().write(("#" + appInfo.getAppName() + " " + appInfo.getDescription() + " Version=" + appInfo.getCurrentVersion()).getBytes());
					response.getOutputStream().write(lineByte);
					for(AppConfig appConfig:list) {
						response.getOutputStream().write(appConfig.getConfigKey().getBytes());
						response.getOutputStream().write(eqs);
						response.getOutputStream().write(appConfig.getConfigValue().getBytes());
						response.getOutputStream().write(lineByte);
					}
					response.getOutputStream().write(lineByte);
				}
			}
		}
	}
	
	/**
	 * 通过id查询配置历史版本
	 * 
	 * @param id id
	 * @return R
	 */
	@GetMapping("/{id}")
	public R<?> getById(@PathVariable("id") Integer id) {
		return new R(appVersionService.getById(id));
	}

}
